import {ReactNode, useState} from "react";
import "./index.scss";

export type TabItem = {
    title: string;
    content: ReactNode;
};

type TabProps = {
    tabs: TabItem[];
    onTabChange?: (activeIndex: number, activeTab: TabItem) => void; // 回调函数
};

const Tab = ({tabs, onTabChange}: TabProps) => {
    const [activeTab, setActiveTab] = useState<string>(tabs[0].title);

    // 修改 setActiveTab 的逻辑，同时调用 onTabChange
    const handleTabChange = (title: TabItem) => {
        setActiveTab(title.title);
        if (onTabChange) {
            const activeIndex = tabs.indexOf(title);
            onTabChange(activeIndex, title); // 将当前激活的标签页标题传递给父组件
        }
    };

    return (
        <div className="tab">
            {/* 标签页按钮 */}
            <div className="tab-links">
                {tabs.map((tab) => (
                    <div
                        key={tab.title}
                        className={activeTab === tab.title ? "active" : ""}
                        onClick={() => handleTabChange(tab)} // 使用 handleTabChange
                    >
                        {tab.title}
                        <div className="wire"></div>
                    </div>
                ))}
            </div>

            {/* 标签页内容 */}
            <div>
                {tabs.map((tab) => (
                    <div
                        key={tab.title}
                        className={"tab-content " + (activeTab === tab.title ? "tab-content-active" : "")}
                    >
                        {tab.content}
                    </div>
                ))}
            </div>
        </div>
    );
};

export default Tab;